package main

import (
	"context"
	"gitee.com/kinwyb/appTools/appTool"
	"gitee.com/kinwyb/appTools/common"
	"gitee.com/kinwyb/appTools/log"
	"gitee.com/kinwyb/appTools/manager"
	"gitee.com/kinwyb/conv"
	"github.com/sirupsen/logrus"
	"os"
	"path/filepath"
	"strings"
)

var app = appTool.NewApplication("managerClient")
var defaultAppDir = "./"

func main() {
	appTool.Version = "1.1.13"
	app.SetAppDescription("应用管理客户端,兼容server 1.0.3")
	app.IgnoreConfigCheck()
	app.Flag().StringVarP(&serverAddress, "server", "s", defaultServerAddress(), "服务端地址")
	app.Flag().StringVarP(&tag, "tag", "t", defaultTag(), "tag标记")
	app.Flag().StringVarP(&appName, "app", "a", defaultAppName(), "应用名称")
	app.Flag().StringVarP(&defaultAppDir, "path", "p", "./app", "运行文件目录")
	app.RunFunc(func(ctx context.Context) {
		// 日志输出到文件
		logToConsole := conv.ToBool(os.Getenv("LOG_TO_CONSOLE"))
		log.SetLogFile("./manager.log", logrus.InfoLevel, !logToConsole)
		log.SetLogEnv("pro")
		dir, err := filepath.Abs(defaultAppDir)
		if err == nil {
			defaultAppDir = dir
		}
		// 检测运行目录是否存在,不存在就新建一个
		_, err = os.Stat(defaultAppDir)
		if os.IsNotExist(err) {
			err := os.MkdirAll(defaultAppDir, 0777)
			if err != nil {
				manager.ServiceLog.WithField("info", defaultAppDir).Error("无法创建运行目录")
				return
			}
		}
		initConnect(ctx) // 连接服务器
		initProcess()
		<-ctx.Done()
	}).Run()
}

const (
	envServerAddress = "CAGENT_SERVER_ADDRESS" //服务地址环境变量
	envAppName       = "CAGENT_APP"            //应用名称
	envTag           = "CAGENT_TAG"            //环境标记
	envClientID      = "CAGENT_CLIENT_ID"      //客户端ID
)

// 获取应用名称
func defaultAppName() string {
	return os.Getenv(envAppName)
}

// 默认服务器地址
func defaultServerAddress() string {
	address := os.Getenv(envServerAddress)
	if address == "" {
		return "127.0.0.1:9998"
	}
	return address
}

// 环境tag标签
func defaultTag() string {
	envTagVal := os.Getenv(envTag)
	if envTagVal == "" {
		envTagVal = "TAG" + common.IDGen()
	}
	return envTagVal
}

// 获取客户端ID
func getClientID() string {
	id := strings.TrimSpace(os.Getenv(envClientID))
	if id != "" {
		return id
	}
	return common.IDGen()
}
